package com.shop.web.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.exception.BusinessException;
import com.shop.web.user.entity.User;
import com.shop.web.user.entity.UserSign;
import com.shop.web.user.mapper.UserSignMapper;
import com.shop.web.user.service.UserService;
import com.shop.web.user.service.UserSignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;

@Service
public class UserSignServiceImpl extends ServiceImpl<UserSignMapper, UserSign> implements UserSignService {

    @Autowired
    private UserService userService;

    @Override
    @Transactional
    public Integer sign(Long userId) {
        // 检查用户是否存在
        User user = userService.getById(userId);
        if (user == null) {
            throw new BusinessException(500, "用户不存在");
        }

        // 检查今日是否已签到
        if (hasSignedToday(userId)) {
            throw new BusinessException(500, "今日已签到");
        }

        // 计算签到积分（这里简单实现，每天固定5积分）
        int points = 5;

        // 创建签到记录
        UserSign sign = new UserSign();
        sign.setUserId(userId);
        sign.setPoints(points);
        sign.setSignTime(new Date());
        sign.setRemark("每日签到");
        this.save(sign);

        // 更新用户积分
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda()
                .set(User::getPoints, user.getPoints() == null ? points : user.getPoints() + points)
                .eq(User::getUserId, userId);
        userService.update(updateWrapper);

        return points;
    }

    @Override
    public boolean hasSignedToday(Long userId) {
        // 获取今天的开始时间和结束时间
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        Date startTime = calendar.getTime();
        
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        Date endTime = calendar.getTime();

        // 查询今日是否已签到
        QueryWrapper<UserSign> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(UserSign::getUserId, userId)
                .between(UserSign::getSignTime, startTime, endTime);
        
        return this.count(queryWrapper) > 0;
    }
} 